<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1===0? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children"
              :key="item1.id ">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二/三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2 ) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" type="warning" closable
                      @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click='showEditDialog(scope.row.id)'>编辑
            </el-button>
            <!-- 编辑用户对话框 -->
            <el-dialog title="编辑用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
              <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
                <el-form-item label="角色名称" prop="roleName" width='40px'>
                  <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                  <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo()">确 定</el-button>
              </span>
            </el-dialog>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUserById(scope.row.id)">
              删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="dfkeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  export default {
    data() {
      return {
        //添加修改用户信息表单验证规则
        editFormRules: {
          roleDesc: [{
              required: true,
              message: '请输入角色描述',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10个字符',
              trigger: 'blur'
            }
          ],
          roleName: [{
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10个字符',
              trigger: 'blur'
            }
          ]
        },
        //查询到的用户信息对象
        editForm: {},
        //控制修改用户信息对话框隐藏
        editDialogVisible: false,
        //树形控件的属性绑定对象
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        //控制分配权限对话框的显示与隐藏
        setRightDialogVisible: false,
        //所有角色列表数据
        roleList: [],
        rightList: [],
        //默认选中的节点ID值数组
        dfkeys: [],
        //当前即将分配权限的角色ID
        roleId: ''
      }
    },
    created() {
      this.getRoleList()
    },
    methods: {
      async removeUserById(id) {
        //弹框询问用户是否删除信息
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info(`已取消删除`)
        }
        const {
          data: res
        } = await this.$axios.delete('roles/' + id)
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(`删除失败`)
        }
        this.$message.success(`删除角色成功!`)
        this.getRoleList()
      },
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      async showEditDialog(id) {
        const {
          data: res
        } = await this.$axios.get('roles/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error(`查询用户信息失败`)
        }
        this.editForm = res.data
        this.editDialogVisible = true
      },
      //点击为角色分配权限
      async allotRights() {
        const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
        console.log(keys);
        const idStr = keys.join(',')
        const {
          data: res
        } = await this.$axios.post(`roles/${this.roleId}/rights`, {
          rids: idStr
        })
        if (res.meta.status !== 200) {
          return this.$message.error(`分配权限失败`)
        }
        this.$message.success(`分配权限成功`)
        this.getRoleList()
        this.setRightDialogVisible = false
      },
      //监听分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.dfkeys = []
      },
      //通过递归的形式获取角色下所有三级权限的id ,并保存到dfkeys
      getLeafKeys(node, arr) {
        //如果当前node节点不包含children属性,则是三级节点
        if (!node.children) {
          return arr.push(node.id)
        }
        //没有return 则不是三级节点
        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      //展示分配权限的对话框
      async showSetRightDialog(role) {
        this.roleId = role.id
        //获取所有权限的数据
        const {
          data: res
        } = await this.$axios.get('rights/tree')
        if (res.meta.status !== 200) {
          return this.$message.error(`获取列表失败`)
        }
        this.rightList = res.data
        console.log(this.rightList);
        //递归获取三级节点的id
        this.getLeafKeys(role, this.dfkeys)

        this.setRightDialogVisible = true
      },
      async removeRightById(role, id) {
        //弹框确认是否取消
        const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => err);
        if (confirmResult !== 'confirm') {
          return this.$message.info('取消了删除!')
        }
        // console.log(`确认了删除`);
        const {
          data: res
        } = await this.$axios.delete(`roles/${role.id}/rights/${id}`)
        if (res.meta.status != 200) {
          return this.$message.error(`删除权限失败`)
        }
        this.$message.success(`删除权限成功`)
        // this.getRoleList() 会发生全页面渲染
        role.children = res.data //只渲染修改展开列表
      },
      async getRoleList() {
        const {
          data: res
        } = await this.$axios.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error(`获取角色列表失败`)
        }
        this.roleList = res.data
        // console.log(this.roleList);
      },
      //修改表单信息的预验证
      editUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$axios.put('roles/' + this.editForm.roleId, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          })
          console.log(res);
          console.log(this.editForm.roleId);


          if (res.meta.status !== 200) {
            return this.$message.error(`更新用户信息失败!`)
          }
          this.editDialogVisible = false
          this.getRoleList()
          this.$message.success(`更新用户信息成功`)
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

  .element.style {
    width: 86px;
  }
</style>